<script setup lang="ts">
import { reactive, shallowRef, computed, ref, nextTick } from 'vue';
import { useLargenScreen } from '@/composables/useLargenScreen';
import { useRoute } from 'vue-router';
import getCode from './components/getCode.vue';
import bg1 from '@/assets/images/register/login-bg1.webp';
import type { FormInstance } from 'vant';
import { register, sysconfig } from '@/common/api/register';
import { showSuccessToast, showToast } from 'vant';
import { isWeChat } from '@/utils/util';
import guidePag from './components/guidePage.vue';

// 定义组件引用
const formRef = shallowRef<FormInstance>();
const guidePagRef = shallowRef<InstanceType<typeof guidePag>>();

const route = useRoute();
// 监听浏览器窗口变化
const [largenScreen] = useLargenScreen();

const loading = ref(false);
const download = reactive({
  android: '',
  ios: '',
});
const form = reactive<Record<string, string>>({
  mobile: '',
  password: '',
  smscode: '',
  yqcode: '',
});
const emptyForm = JSON.stringify(form);

const submitDisabled = computed(() => Object.keys(form).some((key) => !form[key]));

if (route.query?.inviteCode) {
  form.yqcode = route.query.inviteCode as string;
}

const onSubmit = async () => {
  loading.value = true;
  try {
    await register({ ...form });
    Object.assign(form, JSON.parse(emptyForm));
    showSuccessToast('注册成功');
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};

const getSysConfig = async () => {
  try {
    const res = await sysconfig({});
    const configList = res.result.list;
    const android = configList.find((v: any) => v.cfg_key === 'k5');
    if (android) {
      download.android = JSON.parse(android.cfg_value)?.weburl || '';
    }
    const ios = configList.find((v: any) => v.cfg_key === 'k6');
    if (ios) {
      download.ios = JSON.parse(ios.cfg_value)?.url || '';
    }
  } catch {
    /** empty */
  }
};
getSysConfig();

const onVerifyMobile = () => {
  formRef.value?.validate('mobile');
};

const handleDownload = (type: 'android' | 'ios') => {
  if (!download[type]) {
    return showToast('敬请期待');
  }
  if (isWeChat()) {
    return guidePagRef.value?.open();
  }
  if (type === 'android') {
    const form = document.createElement('form');
    form.action = download.android;
    document.getElementsByTagName('body')[0].appendChild(form);
    form.submit();
    nextTick(() => {
      document.removeChild(form);
    });
  } else {
    window.location.href = download.ios;
  }
};
</script>
<template>
  <div
    class="register bg-[length:100%_auto] bg-no-repeat"
    :class="{ boxShadow: largenScreen }"
    :style="{ backgroundImage: `url(${bg1})` }"
  >
    <div class="text-white px-8">
      <div class="text-3xl font-bold">免费注册</div>
      <div class="mt-1">欢迎注册国华商城极速版会员！</div>
      <div class="w-[53px] h-[2px] rounded-sm bg-white mt-3"></div>
    </div>
    <div class="mt-[110px]">
      <van-form ref="formRef" @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="form.mobile"
            maxlength="11"
            size="large"
            name="mobile"
            placeholder="请输入手机号"
            :rules="[{ required: true, message: '请填写手机号' }]"
          />
          <van-field
            v-model="form.password"
            size="large"
            type="password"
            name="password"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <van-field
            v-model="form.smscode"
            size="large"
            name="smscode"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #button>
              <getCode :mobile="form.mobile" @on-verify-mobile="onVerifyMobile" />
            </template>
          </van-field>
          <van-field
            v-model="form.yqcode"
            size="large"
            name="yqcode"
            placeholder="请输入邀请码"
            :rules="[{ required: true, message: '请填写邀请码' }]"
          />
        </van-cell-group>
        <div class="mx-8 mt-6">
          <van-button
            round
            block
            type="primary"
            :loading="loading"
            :disabled="submitDisabled"
            color="linear-gradient(-90deg, #FA1C43, #FF441F)"
            native-type="submit"
          >
            提交
          </van-button>
        </div>
      </van-form>
      <div class="flex justify-center items-center px-8 mt-6">
        <van-button
          class="!mr-5 shadow"
          round
          block
          type="primary"
          color="linear-gradient(-90deg, #FA1C43, #FF441F)"
          @click="handleDownload('android')"
        >
          安卓下载
        </van-button>
        <van-button
          class="shadow"
          round
          block
          type="primary"
          color="linear-gradient(-90deg, #FA1C43, #FF441F)"
          @click="handleDownload('ios')"
        >
          ISO下载
        </van-button>
      </div>
    </div>
    <!-- 引导页 -->
    <guidePag ref="guidePagRef" />
  </div>
</template>
<style lang="less" scoped>
.register {
  padding: 80px 0 30px;
  max-width: 450px;
  margin: 0 auto;
}
.register.boxShadow {
  margin: 3vh auto;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.18);
}
</style>
